# -*- encoding: utf-8 -*-
##############################################################################
#
##############################################################################

from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_round


# 批量取消
class mrp_production_wizard_multi_cancel(models.TransientModel):
    _name = 'mrp.production.wizard.multi.cancel'

    @api.multi
    def mrp_production_wizard_multi_cancel(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', []) or []
        proxy = self.env['mrp.production']
        for record in proxy.browse(active_ids):
            if record.state != 'done':
                record.action_cancel()
        return {'type': 'ir.actions.act_window_close'}


# 通过生产单创建合并
class mrp_production_wizard_create(models.TransientModel):
    _name = 'mrp.production.wizard.create'

    picking_type_id = fields.Many2one("stock.picking.type", string=u"作业类型", required=True)
    department_id = fields.Many2one("hr.department", string="部门", required=True)

    @api.multi
    def mrp_production_wizard_create_create(self):
        context = dict(self._context or {})
        active_ids = context.get('active_ids', []) or []
        proxy = self.env['mrp.production']
        order_obj = self.env['mrp.production.merge']
        order_merge = order_obj.create({
            "picking_type_id": self.picking_type_id.id,
            "department_id": self.department_id.id
        })
        for record in proxy.browse(active_ids):
            if record.state != 'confirmed':
                active_ids.remove(record.id)
        for record in proxy.browse(active_ids):
            # 给生产单赋值
            if not record.production_merge_id:
                record.production_merge_id = order_merge.id
                for move_line in record.move_raw_ids:
                    move_line.production_merge_id = order_merge.id
        return {'type': 'ir.actions.act_window_close'}


# 合并的单子创建新明细。创建的时候需要选择分配生产单。然后添加的时候，自动给生产单添加明细。
class add_new_line_production(models.TransientModel):
    _name = 'add.new.line.production'

    new_line_id = fields.Many2one('add.new.line', string=u'添加的明细')
    product_id = fields.Many2one('product.product', string=u'产品')
    product_qty = fields.Float(string=u'生产数量')
    production_id = fields.Many2one('mrp.production', string=u'生产单')
    distribution_qty = fields.Float(string=u'分配数量', default=0.0)


class add_new_line(models.TransientModel):
    _name = 'add.new.line'
    _description = 'QC Transfer'

    merge_id = fields.Many2one('mrp.production.merge')
    product_id = fields.Many2one('product.product', string=u'产品')
    product_qty = fields.Float(string=u'数量', default=0)
    product_qty_sum = fields.Float(string=u'数量', default=0, compute='_get_sum_qty')
    production_ids = fields.One2many('add.new.line.production', 'new_line_id', string=u'生产单')

    @api.depends('production_ids')
    def _get_sum_qty(self):
        if self.production_ids:
            sum_qty = 0
            for line in self.production_ids:
                sum_qty += line.distribution_qty
            self.product_qty_sum = sum_qty

    @api.model
    def default_get(self, fields):
        res = super(add_new_line, self).default_get(fields)
        if not res.get('merge_id') and self._context.get('active_id'):
            line_production = []
            res['merge_id'] = self._context['active_id']
            merge_id = self.env['mrp.production.merge'].browse(self._context.get('active_id'))
            for mrp_production in merge_id.mrp_production_ids:
                line_production.append((0, 0, {
                    # 'new_line_id':self.id,
                    'product_id': mrp_production.product_id.id,
                    'product_qty': mrp_production.product_qty,
                    'production_id': mrp_production.id,
                }))
            res['production_ids'] = line_production
        return res

    @api.multi
    def change_prod_qty(self):
        sum = 0
        bom_line_obj = self.env['mrp.bom.line']
        merge_line_obj = self.env['mrp.production.merge.line']
        merge_line = merge_line_obj.create({
            'production_merge_id': self.merge_id.id,
            'product_id': self.product_id.id,
            'name': self.product_id.display_name,
            'quantity_ready': 0.0,
            'quantity_done': 0.0,
            'uom_id': self.product_id.uom_id.id,
        })
        for item in self.production_ids:
            if item.distribution_qty <= 0:
                continue
            bom_line = bom_line_obj.create({
                'product_id': self.product_id.id,
                'product_qty': item.distribution_qty,
                'bom_id': item.production_id.bom_id.id
            })
            sum += item.distribution_qty
            move = item.production_id._generate_raw_move(bom_line, {'qty': item.distribution_qty, 'parent_line': None})
            item.production_id._adjust_procure_method()
            move.action_confirm()
            move.production_merge_id = self.merge_id.id
            move.production_merge_line_id = merge_line.id
            move.merged = True
            bom_line.unlink()
        if sum <> self.product_qty:
            raise ValidationError(u'分配到生产单上的数量合计不等于添加的产品的数量！')
        self.merge_id.set_open()


class ChangeProductionQty(models.TransientModel):
    _inherit = 'change.production.qty'

    @api.multi
    def change_prod_qty(self):
        res = super(ChangeProductionQty, self).change_prod_qty()
        return {'type': 'ir.actions.client', 'tag': 'reload'}
